import { Collection, DatasetListItem, MAX_NAME_LENGTH, GetGroupTreeList } from '@/common';
import datasetService from '@/api/services/datasetService';
import { useEffect, useState } from 'react';
import {
  Button,
  Dropdown,
  Empty,
  Input,
  MenuProps,
  message,
  Modal,
  Space,
  Splitter,
  Table,
  Typography,
} from 'antd';
import {
  CloseOutlined,
  DeleteOutlined,
  EditOutlined,
  EllipsisOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import '../styles/api.scss';
import { SvgIcon } from '@/components/icon';
import dayjs from 'dayjs';
import { useUpdateEffect } from 'react-use';
import { useDebounceFn } from 'ahooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
// import EmptyPape from '@/components/empty/EmptyPage';
import NotData from '@/components/NotData';
import { Size } from '@/types/common';
import { useContextSelector } from 'use-context-selector';
import { ApiManageContext } from '../context';
import { ApiDatasetEvent } from '@/types/api';
import { CircleLoading } from '@/components/loading';
import { useDatasetStore } from '@/store/datasetStore';
import { useRouter, useParams } from '@/router/hooks';
import { useUserInfo } from '@/store/userStore';
import { TreeData } from '@/types/dataset';
import NewDatasetModal from './NewDatasetModal';
import { formatDataWithSeconds } from '@/utils/time';
import Tables from '@/components/tables/tables';
import EmptyTip from '@/components/EmptyTip';
const { Text } = Typography;

interface Props {
  datasets: DatasetListItem[];
  groupId: string | undefined;
  managers: any;
  approves: any;
  isAdmin: boolean;
  isPermit: boolean;
  parentSize: Size;
  loading: boolean;
  total: number;
  pageSize: number;
  page: number;
  searchValue?: string;
  setSearchValue?: (value: string) => void;
  onItemClicked?: (item: DatasetListItem | undefined) => void;
  handlePageChange?: (page: number, pageSize: number) => void;
}
const ApiTable = ({
  datasets,
  isAdmin,
  isPermit,
  parentSize,
  loading,
  onItemClicked,
  handlePageChange,
  groupId,
  managers,
  total,
  approves,
  pageSize,
  page,
  searchValue,
  setSearchValue,
}: Props) => {
  const { loadAllDatasets1 } = useDatasetStore();
  // const [total, setTotal] = useState(0);
  // const [page, setPage] = useState(1);
  // const [pageSize, setPageSize] = useState(10);
  const [parentId, setParentId] = useState<string | null>('');
  // const [searchValue, setSearchValue] = useState('');
  // const [loading, setLoading] = useState(false);
  const [renameModalVisible, setRenameModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedRows, setSelectedRows] = useState<Collection[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [newName, setNewName] = useState('');
  const [isBatchDelete, setIsBatchDelete] = useState(false);
  const [editItem, setEditItem] = useState<Collection | undefined>(undefined);
  const { isPc } = useWindowWidth();
  const { event$ } = useContextSelector(ApiManageContext, (s) => s);
  const { role } = useUserInfo();
  const { appId = '' } = useParams() as { appId: string };
  const [dataList, setDataList] = useState<DatasetListItem[]>([]);
  const [newDatasetModalVisible, setNewDatasetModalVisible] = useState(false);
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: Collection[]) => {
      console.log(selectedRowKeys, selectedRows);
      setSelectedRows(selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
    selectedRowKeys: selectedRowKeys,
  };

  const columns = [
    {
      // title: <div>全部文档 ({total})</div>,
      title: '数据接口',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => (
        <div className="items-cente flex w-full gap-2">
          <SvgIcon icon="dataset-icon-jianbian" size={20} />
          <Text ellipsis={{ tooltip: name }}>{name}</Text>
        </div>
      ),
    },
    {
      title: '数据源',
      dataIndex: 'openapiUrl',
      key: 'openapiUrl',
      render: (openapiUrl: string) => (
        <Text ellipsis={{ tooltip: openapiUrl }}>{openapiUrl ? openapiUrl : '-'}</Text>
      ),
    },
    {
      title: '时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (updateTime: string) => (
        <span>{dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: '100px',
      render: (_, record: DatasetListItem) => (
        <Space size="small">
          {isAdmin ? (
            <div className="flex cursor-pointer items-center gap-2 text-@brand-color">
              <Button
                type="text"
                style={{
                  background: 'none',
                  border: 'none',
                  font: 'inherit',
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  setEditItem(record);
                  setNewDatasetModalVisible(true);
                }}
              >
                <SvgIcon icon="singleedit" />
                修改
              </Button>

              <Button
                type="text"
                danger
                style={{
                  background: 'none',
                  border: 'none',
                  font: 'inherit',
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  setEditItem(record);
                  setDeleteModalVisible(true);
                }}
              >
                <SvgIcon icon="deltongbu" />
                删除
              </Button>
            </div>
          ) : (
            '-'
          )}
        </Space>
      ),
      // onCell: () => ({ style: { width: '300px' } }),
    },
  ];

  const getDatasets = async () => {
    try {
      //获取知识库数据
      const res: any = await loadAllDatasets1({
        parentId: parentId,
        page: page,
        page_size: pageSize,
        offset: (page - 1) * pageSize,
        searchText: '',
        groupId: '',
        isPage: true,
        app_id: appId || '67fcd7c1de9ddb56bea37b6c', //必填
        dataset_type: 'function',
      });
      setDataList(res.list);
      // setTotal(res.total);
    } catch (error) {
    } finally {
    }
  };

  const handleConfirmNewDataset = async (name: string) => {
    const newName = name?.trim();
    if (!newName) {
      message.error('请输入名称');
      return;
    }
    await datasetService.updateKnowledgeBase({
      dataset_id: editItem?.id,
      parentId: null,
      app_id: appId,
      type: 'function',
      name: newName,
      intro: '',
      avatar: '/imgs/dataset/dataset.svg',
      vectorModel: '',
      agentModel: '',
      openapiUrl: '',
      dataset_tags: [''],
      groupId: groupId,
      assessor: approves.map((item) => item?.id),
      administrator: managers.map((item) => item?.id),
      uploader: [],
      dataset_type: 'function',
    });
    message.success('修改成功');
    // setPage(1);
    // setPageSize(10);
    // getDatasets();
    setNewDatasetModalVisible(false);
    event$?.emit(ApiDatasetEvent.REFRESHDATASET);
  };

  // const handlePageChange = (page: number, pageSize: number) => {
  //   setPage(page);
  //   setPageSize(pageSize);
  // };

  const paginationConfig = {
    current: page,
    pageSize: pageSize,
    pageSizeOptions: undefined,
    total: total,
    onChange: handlePageChange,
  };

  const clearSelections = () => {
    setSelectedRows([]);
    setSelectedRowKeys([]);
  };

  const rename = async () => {
    const newNameRename = newName.trim();
    if (!newNameRename) {
      message.error('名称不能为空');
      return;
    }
    if (newNameRename.length > MAX_NAME_LENGTH) {
      message.error(`名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
      return;
    }
    if (!editItem) {
      return;
    }
    await datasetService.datasetUpdate({
      id: editItem?._id,
      name: newNameRename, // 假设 newName 是新的名称
    });
    message.success('修改名称成功！');
    event$?.emit(ApiDatasetEvent.REFRESHDATASET);
    setRenameModalVisible(false);
    setEditItem(undefined);
  };

  const handleDeleteConfirm = async () => {
    if (isBatchDelete) {
      const promises = selectedRows.map(async (row) => {
        await datasetService.datasetDelete({
          id: [row?.id],
          reviewStatus: 'drop',
          app_id: appId,
        });
      });

      await Promise.all(promises);
    } else {
      if (!editItem) {
        return;
      }
      await datasetService.datasetDelete({
        id: [editItem?.id],
        reviewStatus: 'drop',
        app_id: appId || '67fcd7c1de9ddb56bea37b6c',
      });
    }
    message.success('删除成功！');
    // setPage(1);
    // setPageSize(10);
    // getDatasets();
    setDeleteModalVisible(false);
    setEditItem(undefined);
    setIsBatchDelete(false);
    clearSelections();
    event$?.emit(ApiDatasetEvent.REFRESHDATASET);
  };

  const handleBatchDelete = async () => {
    setIsBatchDelete(true);
    setDeleteModalVisible(true);
  };

  const handleRowClick = (record: DatasetListItem) => {
    onItemClicked && onItemClicked(record);
  };

  useEffect(() => {
    setDataList(datasets);
  }, [datasets]);

  return (
    <>
      {/* {loading && <CircleLoading />} */}
      <div className="relative flex h-full flex-col gap-4 overflow-y-auto">
        <div className="left-0 top-2 z-10 w-[200px]">
          <Input
            placeholder="请输入内容"
            onChange={(e) => {
              setSearchValue && setSearchValue(e.target.value);
              handlePageChange && handlePageChange(1, pageSize);
            }}
            value={searchValue}
            suffix={<SvgIcon icon="work-ic6" size={16} />}
            className=" !rounded-md"
            style={{
              height: '32px',
              width: '240px',
            }}
          />
        </div>
        <Tables
          rowClassName="bg-[#fff] custom-scrollbar"
          className="custom-scrollbar"
          dataSource={dataList}
          columns={columns}
          rowSelection={isAdmin ? rowSelection : {}}
          rowKey={'id'}
          onRow={(record) => {
            return {
              onClick: () => handleRowClick(record), // 点击行时触发
            };
          }}
          pagination={false}
          // rowBgClassName="bg-[#F6F7FB]"
          // scroll={scroll}
          paginationProps={paginationConfig}
          locale={{
            emptyText: (
              <div style={{ textAlign: 'center', color: '#999' }}>{!loading && <EmptyTip />}</div>
            ),
          }}
        />
      </div>

      {selectedRows.length > 0 && isAdmin && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={clearSelections}
            ></Button>
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRows.length} 项
            </span>
            <Splitter />

            <Button style={{ color: '#fff' }} type="text" onClick={handleBatchDelete}>
              删除
            </Button>
          </Space>
        </div>
      )}

      <Modal
        title={<div style={{ textAlign: 'center', width: '100%' }}>重命名</div>}
        open={renameModalVisible}
        onCancel={() => {
          setRenameModalVisible(false);
        }}
        okText="确定"
        cancelText="取消"
        closable={false}
        width={300}
        centered
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size={56}>
              <Button
                onClick={() => {
                  setRenameModalVisible(false);
                }}
              >
                取消
              </Button>
              <Button type="primary" onClick={rename}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input value={newName} onChange={(e) => setNewName(e.target.value)} />
        </div>
      </Modal>

      <DeleteConfirmModal
        visible={deleteModalVisible}
        text={`确定要删除吗？`}
        onCancel={() => {
          setDeleteModalVisible(false);
        }}
        onConfirm={handleDeleteConfirm}
      />
      <NewDatasetModal
        title="编辑数据接口集"
        editType="update"
        onConfirm={handleConfirmNewDataset}
        onCancel={() => {
          setNewDatasetModalVisible(false);
        }}
        updateDataset={editItem}
        open={newDatasetModalVisible}
      />
    </>
  );
};

export default ApiTable;
